package org.malred.hospital.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.malred.hospital.common.BaseContext;
import org.malred.hospital.common.R;
import org.malred.hospital.dto.LoginDto;
import org.malred.hospital.dto.LoginForm;
import org.malred.hospital.entity.*;
import org.malred.hospital.service.*;
import org.malred.hospital.utils.ConstValues;
import org.malred.hospital.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Pattern;

/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
//@CrossOrigin(origins = "*",maxAge = 3600)
@Slf4j
public class CommonController {

    @Autowired
    private StudentAccountService studentAccountService;
    @Autowired
    private DoctorAccountService doctorAccountService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private StudentService studentService;
    @Autowired
    private DoctorService doctorService;


    @Value("${reggie.path}")
    private String basePath;
    @Value("${jwt.data.header}")
    private String header;

    /**
     * 文件上传
     *
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        log.info(file.toString());

        //原始文件名
        String originalFilename = file.getOriginalFilename();//abc.jpg
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;//dfsdfdfd.jpg

        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在，需要创建
            dir.mkdirs();
        }

        try {
            //将临时文件转存到指定位置
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    /**
     * 文件下载
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {

        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //输出流，通过输出流将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }

            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @PostMapping("/login")
    public R<LoginDto> login(@RequestBody LoginForm form) {
        LoginDto dto = new LoginDto();
        String username = form.getUsername();
        String password = form.getPassword();
//        Boolean isStudent = form.getIsStudent();

        if (password.length() < 8 || password.length() > 16) {
            return R.error("密码格式错误! 密码必须是6~16位.");
        }

        if (password.matches(ConstValues.OTHER_CHAT_REGEX)) {
            return R.error("密码格式错误! 密码不能包含特殊字符.");
        }
        if (!password.matches(ConstValues.EN_CHAT_REGEX)
                && !password.matches(ConstValues.NUMBER_REGEX)) {
            return R.error("密码格式错误! 密码至少应包含字母或数字.");
        }

        String role = form.getRole();

        JWTUtils jwtUtils = new JWTUtils();

//        if (isStudent) {
        if (role.equals("1")) {
            LambdaQueryWrapper<TbStudentAccount> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TbStudentAccount::getUsername, username);
            queryWrapper.eq(TbStudentAccount::getPassword, password);
            TbStudentAccount one = studentAccountService.getOne(queryWrapper);

            if (one == null) {
                return R.error("账号或密码错误");
            }

            TbStudent student = studentService.getById(one.getStudentId());
            dto.setRole("student");
            dto.setStudent(student);
            dto.setNickname(one.getNickname());
            dto.setUsername(one.getUsername());
            dto.setToken(
                    jwtUtils.createToken(student.getId(), "student")
            );

            return R.success(dto);
        }

        if (role.equals("2")) {
            LambdaQueryWrapper<TbDoctorAccount> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TbDoctorAccount::getUsername, username);
            queryWrapper.eq(TbDoctorAccount::getPassword, password);
            TbDoctorAccount one = doctorAccountService.getOne(queryWrapper);

            if (one == null) {
                return R.error("账号或密码错误");
            }

            TbDoctor doctor = doctorService.getById(one.getDoctorId());
            dto.setRole("doctor");
            dto.setDoctor(doctor);
            dto.setNickname(one.getNickname());
            dto.setUsername(one.getUsername());
            dto.setToken(
                    jwtUtils.createToken(doctor.getId(), "doctor")
            );

//            BaseContext.setCurrentId(one.getDoctorId());
            return R.success(dto);
        }

        // 管理
        if (role.equals("3")) {
            LambdaQueryWrapper<TbAdminAccount> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TbAdminAccount::getUsername, username);
            queryWrapper.eq(TbAdminAccount::getPassword, password);
            TbAdminAccount one = adminService.getOne(queryWrapper);

            if (one == null) {
                return R.error("账号或密码错误");
            }

            dto.setRole("admin");
            dto.setUsername(one.getUsername());
            dto.setToken(
                    jwtUtils.createToken(one.getId(), "admin")
            );

//            BaseContext.setCurrentId(one.getId());
            return R.success(dto);
        }
        return R.error("登录错误");
    }

    @GetMapping("/is-auth")
    public R<LoginDto> auth(@RequestHeader Map<String, String> headers) {
        String token = headers.get("authorization");
        token = token.replace("Bearer ", "");
        Claims claims = new JWTUtils().parseToken(token);

        String subject = claims.getSubject();
        String id = subject.substring(0, subject.indexOf(':'));
        String role = subject.substring(subject.indexOf(':') + 1);

        // 过期
        Date expiration = claims.getExpiration();
        System.out.println(expiration);
        if (new JWTUtils().judgeTokenExpiration(expiration)) {
            return R.error("登录已过期, 请重新登录");
        }

        LoginDto dto = new LoginDto();
        dto.setToken(token);
        dto.setRole(role);

        if (role.equals("student")) {
            TbStudent one = studentService.getById(id);
            dto.setStudent(one);

            LambdaQueryWrapper<TbStudentAccount> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TbStudentAccount::getStudentId, id);
            TbStudentAccount account = studentAccountService.getOne(queryWrapper);
            dto.setNickname(account.getNickname());

            return R.success(dto);
        }

        if (role.equals("doctor")) {
            TbDoctor one = doctorService.getById(id);
            dto.setDoctor(one);

            LambdaQueryWrapper<TbDoctorAccount> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(TbDoctorAccount::getDoctorId, id);
            TbDoctorAccount account = doctorAccountService.getOne(queryWrapper);
            dto.setNickname(account.getNickname());

            return R.success(dto);
        }

        if (role.equals("admin")) {
            TbAdminAccount one = adminService.getById(id);
            dto.setUsername(one.getUsername());
            return R.success(dto);
        }
        return R.error("校验失败");
    }
}
